package mysql

import (
	"fmt"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"

	"gin-scaffold/setting"
)

var db *gorm.DB

func Init() (err error) {
	// dsn := "user:pass@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local"
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		setting.Conf.MySQLConfig.User,
		setting.Conf.MySQLConfig.Password,
		setting.Conf.MySQLConfig.Host,
		setting.Conf.MySQLConfig.Port,
		setting.Conf.MySQLConfig.DB,
	)
	db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		return err
	}
	sqlDB, err := db.DB()
	if err != nil {
		return err
	}
	// SetMaxIdleConns 设置空闲连接池中连接的最大数量
	sqlDB.SetMaxIdleConns(setting.Conf.MySQLConfig.MaxIdleConns)
	// SetMaxOpenConns 设置打开数据库连接的最大数量。
	sqlDB.SetMaxOpenConns(setting.Conf.MySQLConfig.MaxOpenConns)
	return nil
}
